import React, { useState, useEffect } from "react";
const Timer = ({ name, isRuning = true, onChange = () => {} }) => {
  const [hours, setHours] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [seconds, setSeconds] = useState(0);
  const getTime = (h = hours, m = minutes, s = seconds) => {
    return (
      (h < 10 ? "0" + h : h) +
      ":" +
      (m < 10 ? "0" + m : m) +
      ":" +
      (s < 10 ? "0" + s : s)
    );
  };
  useEffect(() => {
    const time = localStorage.getItem(name);
    if (time) {
      const [h, m, s] = time.split(":").map(Number);
      setHours(isNaN(h) ? 0 : h);
      setMinutes(isNaN(m) ? 0 : m);
      setSeconds(isNaN(s) ? 0 : s);
    }
  }, [name]);
  useEffect(() => {
    const interval = setInterval(() => {
      if (!isRuning) {
        return;
      }
      // 因为使用set不能及时更新state，所以这里使用克隆对象来更新
      var [h, m, s] = [hours, minutes, seconds];
      s = s + 1;
      if (s === 60) {
        m = m + 1;
        s = 0;
      }
      if (m === 60) {
        h = h + 1;
        m = 0;
      }
      if (h === 24) {
        h = 0;
      }
      setHours(h);
      setMinutes(m);
      setSeconds(s);
      localStorage.setItem(name, getTime(h, m, s));
      onChange(getTime(h, m, s));
    }, 1000);

    return () => {
      clearInterval(interval);
    };
    //使用了对应的set所以不能监听hours，minutes，seconds
    // eslint-disable-next-line
  }, [name, isRuning, onChange, getTime]);

  return <div>{getTime()}</div>;
};

export default Timer;
